import router from './router'
import store from './store'
import getPageTitle from "@/utils/get-page-title.js";
import {getStorageItem} from "@/utils/storage.js";
import { ElMessage } from 'element-plus'
import NProgress from "nprogress";

const whiteList = ['/login', '/home'] // 不重定向白名单
NProgress.configure({showSpinner: false});
router.beforeEach(async (to, from, next) => {
    // 开启进度条
    NProgress.start()
    // 设置页面标题
    document.title = getPageTitle(to.meta.title)
    // 获取token
    const token = getStorageItem('token')

    if (token) {
        console.log(111)
        // 有token，直接进入
        if (to.path === '/login') {
            next({path: '/'})
            //  关闭进度条
            NProgress.done()
        } else {
            const menuList = await store.getters.menuList && store.getters.menuList.length > 0
            if (menuList) {
                next()
            } else {
                try {
                    // 获取用户信息
                    const user = await store.dispatch('users/getUsersInfo')
                    // 获取菜单
                    const menuList = await store.dispatch('users/getRouters', { role: user.role, roleList: user.roleList })
                    // 获取通过遍历后的菜单
                    menuList.length > 0 && await store.dispatch('permission/generateRoutes', menuList)
                    // 跳转到当前页面
                    next({...to, replace: true})
                } catch (error) {
                    // 退出登录
                    await store.dispatch('users/logout')
                    // 重定向到登录页
                    next(`/login?redirect=${to.path}`)
                    // 关闭进度条
                    NProgress.done()
                }
            }
        }
    } else {
        await store.dispatch('permission/generateRoutes')
        // 在白名单里面，直接进入
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            // 不在白名单里面，重定向到登录页并且带上当前页面的路径
            next({path: '/login?redirect=' + to.path})
            NProgress.done()
        }
    }
})

// 关闭进度条
router.afterEach(() => {
    // 关闭进度条
    NProgress.done()
})
